# @FileName  :  agent.py
# @Time      :  2025/7/28 22:34
# @Author    :  Ayanami
# @info      :  Agent相关的CRUD操作

from typing import Optional, List
from tortoise.expressions import Q
# from tortoise.functions import Count
from app.models.models import Agent
from app.schemas.agent import AgentCreate, AgentUpdate


class AgentCRUD:
    """Agent CRUD操作类"""

    @staticmethod
    async def create(agent_data: AgentCreate) -> Agent:
        """创建培训机构"""
        agent = await Agent.create(**agent_data.model_dump())
        return agent

    @staticmethod
    async def get_by_id(agent_id: int) -> Optional[Agent]:
        """根据ID获取培训机构"""
        return await Agent.filter(id=agent_id).prefetch_related("area").first()

    @staticmethod
    async def get_by_credit_code(credit_code: str) -> Optional[Agent]:
        """根据统一社会信用代码获取培训机构"""
        return await Agent.filter(credit_code=credit_code).first()

    @staticmethod
    async def get_list(
            page: int = 1,
            page_size: int = 20,
            search: Optional[str] = None,
            area_id: Optional[int] = None,
            is_approved: Optional[bool] = None,
            order_by: str = "-created_at"
    ) -> tuple[List[Agent], int]:
        """
    获取培训机构列表（分页查询）

    Args:
        page: 页码，从1开始
        page_size: 每页记录数
        search: 搜索关键词（支持机构名称、法人、信用代码模糊搜索）
        area_id: 地区ID过滤
        is_approved: 审核状态过滤（True-已审核，False-未审核，None-不过滤）
        order_by: 排序字段（默认按创建时间倒序）

    Returns:
        tuple: (机构列表, 总记录数)
        """
        query = Agent.filter(is_deleted=False).prefetch_related("area")

        # 搜索条件
        if search:
            query = query.filter(
                Q(name__icontains=search) |
                Q(legal_person__icontains=search) |
                Q(credit_code__icontains=search)
            )

        # 地区过滤
        if area_id is not None:
            query = query.filter(area_id=area_id)

        # 审核状态过滤
        if is_approved is not None:
            query = query.filter(is_approved=is_approved)

        # 排序
        query = query.order_by(order_by)

        # 分页
        total = await query.count()
        offset = (page - 1) * page_size
        agents = await query.offset(offset).limit(page_size)

        return agents, total

    @staticmethod
    async def update(agent_id: int, agent_data: AgentUpdate) -> Optional[Agent]:
        """更新培训机构信息"""
        agent = await Agent.get_or_none(id=agent_id)
        if not agent:
            return None

        update_data = agent_data.model_dump(exclude_unset=True)
        if update_data:
            await agent.update_from_dict(update_data)
            await agent.save()

        return await Agent.filter(id=agent_id).prefetch_related("area").first()

    @staticmethod
    async def delete(agent_id: int) -> bool:
        """逻辑删除培训机构"""
        agent = await Agent.get_or_none(id=agent_id, is_deleted=False)
        if not agent:
            return False

        agent.is_deleted = True
        await agent.save(update_fields=["is_deleted", "updated_at"])
        return True

    # @staticmethod
    # async def approve(agent_id: int, is_approved: bool) -> Optional[Agent]:
    #     """审核培训机构"""
    #     agent = await Agent.get_or_none(id=agent_id)
    #     if not agent:
    #         return None
    #
    #     agent.is_approved = is_approved
    #     await agent.save()
    #
    #     return await Agent.filter(id=agent_id).prefetch_related("area").first()

    # @staticmethod
    # async def get_statistics() -> Dict[str, Any]:
    #     """获取培训机构统计信息"""
    #     total_count = await Agent.all().count()
    #     approved_count = await Agent.filter(is_approved=True).count()
    #     pending_count = await Agent.filter(is_approved=False).count()
    #
    #     # 按地区统计 - 使用正确的Tortoise ORM语法
    #     area_stats = await Agent.filter(is_approved=True).annotate(
    #         count=Count('id')
    #     ).group_by('area_id').prefetch_related('area').values(
    #         'area_id',
    #         'area__name',
    #         'count'
    #     )
    #
    #     # 格式化统计结果
    #     area_distribution = [
    #         {
    #             "area_id": stat["area_id"],
    #             "area_name": stat["area__name"],
    #             "count": stat["count"]
    #         }
    #         for stat in area_stats
    #     ]
    #
    #     return {
    #         "total_count": total_count,
    #         "approved_count": approved_count,
    #         "pending_count": pending_count,
    #         "area_distribution": area_distribution
    #     }

    # @staticmethod
    # async def check_credit_code_exists(credit_code: str, exclude_id: Optional[int] = None) -> bool:
    #     """检查统一社会信用代码是否已存在"""
    #     query = Agent.filter(credit_code=credit_code)
    #     if exclude_id:
    #         query = query.exclude(id=exclude_id)
    #     return await query.exists()


agent_crud = AgentCRUD()